package cn.jiyun.web.controller;

import cn.jiyun.dao.domain.Role;
import cn.jiyun.dao.domain.User;
import cn.jiyun.service.RoleService;
import cn.jiyun.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@Controller
public class LoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;


    @GetMapping("/loginPage")
    public String loginPage() {
        return "login";
    }

    @PostMapping("login")
    public String login(User user,  HttpSession session) {

        if (StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())) {
            session.setAttribute("error", "账户或密码为空");
            return "redirect:/loginPage";
        }
        // 调用service执行登录
        User currentUser = userService.loginUser(user);
        if (currentUser == null) {
            session.setAttribute("error", "用户名或密码错误");
            return "redirect:/loginPage";
        }
        // 移除错误信息；如果没有该属性，则什么都不做
        session.removeAttribute("error");

        // 查询当前用户的角色
        Role role = roleService.findRole(currentUser.getRoleId());
        // 存储当前用户的信息到session
        session.setAttribute("currentUser", currentUser);
        // 存储当前用户角色信息到session
        session.setAttribute("currentRole", role);
        // 重定向到主界面
        return "redirect:stu/findLimit";
    }


    @GetMapping("index")
    public String toIndex() {
        return "index";
    }


    //安全退出
    //安全退出
    @RequestMapping("logout")
    public String logout(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws Exception{
        User currentUser = (User) session.getAttribute("currentUser");

        // 清空session
        request.getSession().invalidate();
        // 清空cookie
        Cookie[] cookies = request.getCookies();
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = new Cookie(cookies[i].getName(), null);
            cookie.setMaxAge(0);
            response.addCookie(cookie);
        }
        return "login";
    }
}